package org.example.java.classloader;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

/**
 * User: ZhangJuntao
 * Date: 13-4-13
 * Time: 下午7:06
 */
class FileSystemClassLoader extends ClassLoader {
  private Path path;

  public FileSystemClassLoader(Path path) {
    this.path = path;
  }

  public Class<?> findClass(String name) throws ClassNotFoundException {
    byte[] b = new byte[0];
    try {
      b = getClassData(name);
    } catch (IOException e) {
      e.printStackTrace();
    }
    return defineClass(name, b, 0, b.length);
  }

  public byte[] getClassData(String className) throws IOException {
    Path classFilePath = classNameToPath(className);
    return Files.readAllBytes(classFilePath);
  }

  public Path classNameToPath(String className) {
    return path.resolve(className.replace('.', File.separatorChar) + ".class");
  }

}

